// ActionScript file
import com.esri.ags.Graphic;
import com.esri.ags.events.DrawEvent;
import com.esri.ags.events.LayerEvent;
import com.esri.ags.events.MapMouseEvent;
import com.esri.ags.geometry.Extent;
import com.esri.ags.geometry.Geometry;
import com.esri.ags.geometry.Polygon;
import com.esri.ags.geometry.Polyline;
import com.esri.ags.symbols.InfoSymbol;
import com.esri.ags.symbols.SimpleFillSymbol;
import com.esri.ags.symbols.SimpleLineSymbol;
import com.esri.ags.symbols.SimpleMarkerSymbol;
import com.esri.ags.tasks.supportClasses.IdentifyParameters;
import com.esri.ags.tasks.supportClasses.IdentifyResult;
import com.esri.ags.tools.*;
import com.esri.ags.utils.JSONUtil;
import gisutil.*;

import events.CommonStringEvent;

import flash.events.*;

import flexlib.mdi.containers.MDIWindow;

import mx.controls.Alert;
import mx.events.FlexEvent;
import mx.events.ItemClickEvent;
import mx.managers.CursorManager;
import mx.rpc.AsyncResponder;

import spark.events.IndexChangeEvent;

static private var url_root:String = "http://10.243.167.114";  
//static private var url_root:String = "http://127.0.0.1";

[Bindable]
private var road_url:String = url_root + "/arcgis/rest/services/guangzhou/road/MapServer" ;

[Bindable]
private var road_rest_url:String = url_root + "/ArcGIS/rest/services/guangzhou/road/MapServer" ;
 
private var selectGraphic:Graphic;
private var graphic:Graphic;
private var lastEditGraphic:Graphic;
private var lastActiveEditTypes:String;

private var toolState:Number = 0;
static private  var SELECT_ROAD:Number = 1 ;

private var queryEventRegionControler :QueryEventAndGisControl = new QueryEventAndGisControl();

[Bindable]private var lastIdentifyResultGraphic:Graphic;

[Bindable]
public var hasSelectRoad:int = 1;

public var excuteQueryImediately:int = 1;


// 选择图层
protected function mapLayerSelecteHandle():void
{
	for each( var  tmp:MDIWindow in 	mdiCanvas.windowManager.windowList )
	{
		if( tmp.title == "图层选择" )
			return ;
	}
	
	var layerControl:GisLayerControl = new GisLayerControl();
	var win:MDIWindow = new MDIWindow();
	win.width = 350;
	win.title = "图层选择";
	layerControl.visible = true;
	win.addChild(layerControl);
	layerControl.map = this.map ;
	
	mdiCanvas.windowManager.add(win);
}

private function map_mapMouseDownHandler(event:MapMouseEvent):void
{
	//trace("MouseDown");
	event.currentTarget.addEventListener(MouseEvent.MOUSE_MOVE, map_mouseMoveHandler);
	event.currentTarget.addEventListener(MouseEvent.MOUSE_UP, map_mouseUpHandler);
}

private function map_mouseMoveHandler(event:MouseEvent):void
{
	//trace("mouseMove\n");
	event.currentTarget.removeEventListener(MouseEvent.MOUSE_MOVE, map_mouseMoveHandler);
	event.currentTarget.removeEventListener(MouseEvent.MOUSE_UP, map_mouseUpHandler);
}

private function map_mouseUpHandler(event:MouseEvent):void
{
	//trace("mouseUp");
	event.currentTarget.removeEventListener(MouseEvent.MOUSE_MOVE, map_mouseMoveHandler);
	event.currentTarget.removeEventListener(MouseEvent.MOUSE_UP, map_mouseUpHandler);
	
	if (event.target is Graphic)
	{
		graphic = Graphic(event.target);
		if (lastEditGraphic !== graphic)
		{
			lastEditGraphic = graphic;
			lastActiveEditTypes = "moveRotateScale"; // make sure move and edit vertices is the 1st mode
		}
		if (graphic.geometry is Polyline || graphic.geometry is Polygon)
		{
			if (lastActiveEditTypes == "moveEditVertices")
			{
				lastActiveEditTypes = "moveRotateScale";
				myEditTool.activate(EditTool.MOVE | EditTool.SCALE | EditTool.ROTATE, [ graphic ]);
			}
			else
			{
				lastActiveEditTypes = "moveEditVertices";
				myEditTool.activate(EditTool.MOVE | EditTool.EDIT_VERTICES, [ graphic ]);
			}
		}
		else if (graphic.geometry is Extent)
		{
			myEditTool.activate(EditTool.MOVE | EditTool.SCALE, [ graphic ]);
		}
		else if (graphic.graphicsLayer == regionSelectGraphicsLayer)
		{
			myEditTool.activate(EditTool.MOVE | EditTool.EDIT_VERTICES, [ graphic ]);
		}
	}
	else
	{
		myEditTool.deactivate();
		lastActiveEditTypes = "moveRotateScale"; // make sure move and edit vertices is the 1st mode
	}
}

private function ClearGraphicLayer():void 
{
	regionSelectGraphicsLayer.clear();

	identityGraphicLayer.clear();
	clickGraphicsLayer.clear();
}
// 开始选择地图区域
protected function tbn_RegionSelectHandler(event:ItemClickEvent):void
{
	toolState = 0;
	
	if( null == event.item )
		return ;
	
	var eventObject:CommonStringEvent = new CommonStringEvent("SelectGeoChanged" , "false" );
	dispatchEvent(eventObject); 
	
	myEditTool.deactivate();
	ClearGraphicLayer();
	selectGraphic = null ;
	
	switch (event.item.label)
	{
		case "SELECT_LAYER":
		{
			mapLayerSelecteHandle();
			break;
		}
		case "POLYGON":
		{
			drawTool.activate(DrawTool.POLYGON);
			break;
		}
		case "EXTENT":
		{
			drawTool.activate(DrawTool.EXTENT);
			break;
		}
		case "CIRCLE":
		{
			drawTool.activate(DrawTool.CIRCLE);
			break;
		}
		case "ELLIPSE":
		{
			drawTool.activate(DrawTool.ELLIPSE);
			break;
		}
		case "SELECT_ROAD":
		{
			toolState = SELECT_ROAD ;
			drawTool.deactivate();
			break;
		}
		case "SELECT_NONE":
		{		
			
			drawTool.deactivate();
			break;
		}				
	}
	
}

// 结束区域选择
protected function drawTool_drawEndHandler(event:DrawEvent):void
{
	// reset after finished drawing a feature
	drawTool.deactivate();
	tbn_Region.selectedIndex = -1;
	trace("end draw")
	//trace( event.graphic.geometry.toString()); // 获取坐标位置
	//trace( JSONUtil.encode( event.graphic.geometry.extent) );
	if( selectGraphic != null )
	{
		myEditTool.deactivate();
		regionSelectGraphicsLayer.clear();
		regionSelectGraphicsLayer.add(event.graphic);
	}
	
	if( event.graphic.geometry is Extent )
	{
		var ex:Extent = event.graphic.geometry as Extent ;
		trace("extent");
	}
	else if( event.graphic.geometry is Polygon )
	{
		var po:Polygon = event.graphic.geometry as Polygon ;
		trace("polygon");
	}
	
	var test:SelectRegion = new SelectRegion();
	test.Build(event.graphic.geometry );
	test.stime= new Date(2012,6,1) ;
	test.etime= new Date(2012,6,20) ;
	trace("---selected region---");
	trace( JSONUtil.encode( test ) )
	trace("-------");
	if( excuteQueryImediately == 1 )
	{
		ramsDataGraphicsLayer.clear();
		queryEventRegionControler.grph = ramsDataGraphicsLayer;
		queryEventRegionControler.ExcuteGisQuery( "region" ,  JSONUtil.encode( test));
	}
	selectGraphic = event.graphic;
	
	var eventObject:CommonStringEvent = new CommonStringEvent("SelectGeoChanged" , "true" );
	dispatchEvent(eventObject); 
}

protected function StartRoadSelection( event:MapMouseEvent ): void 
{
	if( SELECT_ROAD  == toolState)
	{
		clickGraphicsLayer.clear();
		
		var identifyParams:IdentifyParameters = new IdentifyParameters();
		identifyParams.returnGeometry = true;
		identifyParams.tolerance = 3;
		identifyParams.width = map.width;
		identifyParams.height = map.height;
		identifyParams.geometry = event.mapPoint;
		identifyParams.mapExtent = map.extent;
		identifyParams.spatialReference = map.spatialReference;
		
		var clickGraphic:Graphic = new Graphic(event.mapPoint, clickPtSym);
		clickGraphicsLayer.add(clickGraphic);
		
		identifyTask.execute(identifyParams, new AsyncResponder(IdentityResultPrc, IdentifyError, clickGraphic));

	}
}

private function IdentityResultPrc(results:Array, clickGraphic:Graphic = null):void
{
	if (results && results.length > 0)
	{
		var result:IdentifyResult = results[0];
		var resultGraphic:Graphic = result.feature;
		switch (resultGraphic.geometry.type)
		{
			case Geometry.MAPPOINT:
			{
				resultGraphic.symbol = smsIdentify;
				break;
			}
			case Geometry.POLYLINE:
			{
				resultGraphic.symbol = slsIdentify;
				break;
			}
			case Geometry.POLYGON:
			{
				// todo only road return -- polyline
				return ;
				resultGraphic.symbol = sfsIdentify;
				break;
			}
		}
		lastIdentifyResultGraphic = resultGraphic;
		
		var name:String = resultGraphic.attributes.名称 ;
		if(name.length == 0 )
		{
			return ;
		}
		// 显示选择道路相关信息
		// update clickGraphic (from mouse click to returned feature)
		clickGraphic.symbol = new InfoSymbol(); // use default renderer
		clickGraphic.attributes = resultGraphic.attributes;
		var test:SelectRoad = new SelectRoad();
		test.Buid( resultGraphic.geometry);
		test.stime= new Date(2012,6,1) ;
		test.etime= new Date(2012,6,20) ;
		trace( JSONUtil.encode( test) );
		
		if( excuteQueryImediately == 1 )
		{
			ramsDataGraphicsLayer.clear();
			queryEventRegionControler.grph = ramsDataGraphicsLayer;
			queryEventRegionControler.ExcuteGisQuery( "road" ,  JSONUtil.encode( test));
			
		}
	}
}

private function IdentifyError(error:Object, clickGraphic:Graphic = null):void
{
	Alert.show(String(error), "Identify Error");
}


protected function RoadMapLoaded(event:LayerEvent):void
{
	trace("RoadMapLoaded" );
	trace( layer_road.fullExtent );
	trace(map.initialExtent)
	map.initialExtent = layer_road.fullExtent;
	
	trace("RoadMapLoaded ----" );
	
	map.zoomToInitialExtent();
}


public function GetSelectRegion():Graphic 
{
	return selectGraphic;
}


public function SetLeftAppBar( ):void
{
	topAppBar.height = 0;
	topAppBar.visible = false;
	
}
public function ModifyCity( strCity:String):void
{
	if( strCity.length > 0 )
	{
		ltLoadingGis.visible =true;
		road_url = url_root + "/arcgis/rest/services/" + strCity + "/road/MapServer" ;
		road_rest_url = road_url;
		trace( "map url ............." );
		trace( road_url );
		trace( "------------end map url ............." );
		layer_road.refresh();
		layer_road.addEventListener(LayerEvent.UPDATE_END, removeBusyCursor, false, 0, true);
	}
}

private function removeBusyCursor(event : Event):void 
{
	ltLoadingGis.visible =false;
}